package com.cherrish.demo.common.network;

import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author cherrish
 * @time 2018-10-23 17:31
 * @name HttpRequestUtil
 * @desc:
 */
@Slf4j
public class HttpRequestUtil {
    private static HttpURLConnection getConn(String server_url) throws Exception {
        URL url = new URL(server_url);
        if(server_url.toLowerCase().startsWith("https")) {
            HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tm, /*new java.security.SecureRandom()*/null);
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            conn.setSSLSocketFactory(ssf);
            return conn ;
        }
        return  (HttpURLConnection) url.openConnection();
    }

    public static String getFromHttps(String server_url,String userId,String token,String strReqJson) {
        String CONTENT_TYPE = "application/json";
        StringBuilder sb2 = new StringBuilder();
        try {
            HttpURLConnection conn = getConn(server_url);
            conn.setConnectTimeout(45 * 1000);
            conn.setReadTimeout(45 * 1000);
            conn.setDoInput(true);// 允许输入
            conn.setDoOutput(true);// 允许输出
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("charset", "UTF-8");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE);
            conn.setRequestProperty("userId", userId);
            conn.setRequestProperty("token", token);
            DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
            if(null != strReqJson && !"".equals(strReqJson.trim())) {
                outStream.write(strReqJson.getBytes());
            }
            outStream.flush();
            outStream.close();
            conn.connect();
            InputStream in = null;
            int resCode = conn.getResponseCode();
            System.out.println("resCode {} " +resCode);
            if (resCode == 200) {
                in = conn.getInputStream();
                int ch;
                while ((ch = in.read()) != -1) {
                    sb2.append((char) ch);
                }
            }
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb2.toString();
    }
}
